default_encoding = 'utf-8'
# coding: utf-8
from django.views.decorators.csrf import csrf_exempt
from django.http import JsonResponse
from rest_framework.decorators import api_view
import json
from django.db.models import Q, F
from myblog.models import MamahaoTestEmail
from myblog.mamahaoService.baseCode import getResonCode
from django.core import serializers
import logging

logger = logging.getLogger('log')
import re


@csrf_exempt  # 允许跨域访问
@api_view(['POST'])
def getEmail(request):
    """
    :param request:
    :return:获取邮件列表返回
    """
    try:
        emailList = MamahaoTestEmail.objects.all()
        data = json.loads(serializers.serialize("json", emailList))
        print(data)
        response = getResonCode().getSuccess()
        response["data"] = data
        return JsonResponse(response)
    except Exception as e:
        logging.error(e)
        response = getResonCode().getErorr()
        return JsonResponse(response)


@csrf_exempt  # 允许跨域访问
@api_view(['POST'])
def addEmail(request):
    """
    :param request:
    :return:添加修改邮件
    """
    data = json.loads(request.body)
    try:
        receiversList = []
        receivers = data["domains"]
        for i in range(len(receivers)):
            value = receivers[i]["value"]
            receiversList.append(value)

        if data["id"] == "":
            emaillist = MamahaoTestEmail(host=data["host"], port=data["port"], user=data["user"], passWD=data["passWD"],
                                         sender=data["sender"], receivers=receiversList)
        else:
            emaillist = MamahaoTestEmail.objects.get(id=data["id"])
            emaillist.host = data["host"]
            emaillist.port = data["port"]
            emaillist.user = data["user"]
            emaillist.passWD = data["passWD"]
            emaillist.sender = data["sender"]
            emaillist.receivers = receiversList
        emaillist.save()
        response = getResonCode().getSuccess()
        return JsonResponse(response)

    except Exception as e:
        logging.error(e)
        response = getResonCode().getErorr()
        return JsonResponse(response)


@csrf_exempt  # 允许跨域访问
@api_view(['POST'])
def testEmail(request):
    """
    :param request:
    :return:测试邮件发送
    """
    try:
        data = json.loads(request.body)
        receiversList = []
        receivers = data["domains"]
        for i in range(len(receivers)):
            value = receivers[i]["value"]
            receiversList.append(value)
        import smtplib, logging
        from email.header import Header
        from email.mime.text import MIMEText

        host = data["host"]  # SMTP服务器
        port = int(data["port"])
        user = data["user"]  # 用户名
        passWD = data["passWD"]  # 授权密码，非登录密码
        sender = data["sender"]  # 发邮件人
        receivers = receiversList  # 收邮件人
        subject = 'test测试邮件'  # 邮件主题
        content = "~~~邮件已成功发送~~~~"
        meg = MIMEText(content + ' \n mamahaotest', _subtype='html', _charset='utf-8')  # 内容, 格式, 编码
        meg['From'] = user  # 这两种方法都一样的
        meg['From'] = "{}".format(user)
        meg['To'] = ','.join(receivers)
        meg['Subject'] = subject + '(测试链接邮件)'

        smtpObj = smtplib.SMTP_SSL(host, port)  # 启用SSL发信, 端口一般是465
        smtpObj.login(user, passWD)  # 登录验证
        smtpObj.sendmail(sender, receivers, meg.as_string())  # 发送
        response = getResonCode().getSuccess()
        response["msg"] = "邮件发送成功"
        return JsonResponse(response)

    except smtplib.SMTPException as e:
        logger.error(e)
        response = getResonCode().getFail()
        request["msg"] = "邮件发送失败"
        return JsonResponse(response)
    except Exception as e:
        logger.error(e)
        response = getResonCode().getFail()
        response["msg"] = "邮件发送异常，请仔细检查格式"
        return JsonResponse(response)
